<template>
  <div :class="title === 'add' || title === 'check' ?
  'creative_request_upload-body' : 'creative_request_upload-body-edit'">
    <el-form ref="form" :model="form" label-width="150px">
      <div v-for="(creativeRequestDetail, index) in creativeRequestData.creativeRequestDetailList" :key="index">
        <el-row v-if="title === 'check' || title ==='edit'" class="checkRequestHistory">
          <el-col :span="16" style="text-align: right">
            <a @click="creativeRequestHistory(index,creativeRequestDetail)">查看历史需求记录</a>
          </el-col>
          <el-col :span="8" style="text-align: center">
            <el-radio-group v-model="creativeRequestDetail.auditStatus">
              <el-radio size="mini" :label="0" v-if="creativeRequestDetail.auditStatus == 0"
                        disabled>待审
              </el-radio>
              <el-radio size="mini" :label="1"
                        disabled>同意
              </el-radio>
              <el-radio size="mini" :label="2"
                        disabled>拒绝
              </el-radio>
            </el-radio-group>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col span="16">
            <el-form-item label="需求内容 :">
<!--              <el-input id="id-offer-componets-creativerequest-conmponents-request-check-detail-content"-->
<!--                        :readonly="true" type="textarea" v-model="creativeRequestDetail.content"-->
<!--                        :autosize="{ minRows: 4 }"></el-input>-->
              <el-input id="id-offer-componets-creativerequest-conmponents-request-check-detail-content"
                        :readonly="true" type="textarea" v-html="creativeRequestDetail.content"
                        :autosize="{ minRows: 4 }"></el-input>
            </el-form-item>
          </el-col>
          <el-col span="8" label="拒绝描述 :" v-if="creativeRequestDetail.auditStatus==2">
            <el-input id="id-offer-componets-creativerequest-conmponents-request-check-detail-auditComment"
                      :readonly="true" type="textarea" v-model="creativeRequestDetail.auditComment"
                      :autosize="{ minRows: 4 }"></el-input>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="需求内容附件 :">
            <creative-upload ref="upload" mode="readonly" :init-file-list="getFileList(creativeRequestDetail)" :max="5"
                             :data="creativeRequestDetail"></creative-upload>
          </el-form-item>
        </el-row>
        <el-row :gutter="20">
          <el-col>
            <el-form-item label="素材数量 :" class="request_creativeNum">
              <el-input id="id-offer-componets-creativerequest-conmponents-request-check-detail-creativeNum"
                        disabled type="number" size="mini" :min="1" v-model="creativeRequestDetail.creativeNum"
                        style="width: 150px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-form-item label="选择参考素材 :">
            <div class="tabs_creative">
              <div @click="creativeTypeClick(creativeRequestDetail,'creatives')"
                   :class="eventSeq > 0 && creativeRequestDetail.creativeDialogType === 'creatives' ? 'tags_true':'tags_false'"
                   style="width: 50%;border-right: 1px solid rgba(22, 132, 252, 100);cursor: pointer;border-radius: 10px 0 0 10px">
                素材库
              </div>
              <div @click="creativeTypeClick(creativeRequestDetail,'originalCreatives')"
                   :class="eventSeq > 0 && creativeRequestDetail.creativeDialogType === 'originalCreatives' ? 'tags_true':'tags_false'"
                   style="width: 50%;cursor: pointer;border-radius: 0 10px 10px 0">原始参考素材
              </div>
            </div>
            <div>
              <!-- 素材库-->
              <div v-if="eventSeq > 0 && creativeRequestDetail.creativeDialogType === 'creatives' " label="素材库" name="creatives">
                <div class="refCreative">
                  <a @click="downloadCreative(creativeRequestDetail,'creative')" style="margin-left: 20px"><i
                    class="el-icon-download">下载</i></a>
                </div>
                <!-- 素材添加之后的素材回显到这里 -->
                <el-row :gutter="20" class="creative_list" style="margin: 0">
                  <ul class="el-upload-list el-upload-list--picture-card">
                    <li
                      v-for="(creative, i) in creativeRequestDetail.creativeList"
                      :key="i"
                      class="el-upload-list__item is-ready"
                    >
                      <div v-if="creative.thumbnailUrl === '-1'">上传中</div>
                      <div v-if="creative.thumbnailUrl === '-2'">上传失败</div>
                      <img
                        v-if="
                          creative.thumbnailUrl !== '-1' &&
                          creative.thumbnailUrl !== '-2'
                        "
                        class="el-upload-list__item-thumbnail creative"
                        :src="creative.thumbnailUrl"
                        alt=""
                        @click="detailCreative(creative,$event)" showdetail="true"
                      />
                    </li>
                  </ul>
                </el-row>
              </div>
              <!--原始参考材料-->
              <div v-if="eventSeq > 0 && creativeRequestDetail.creativeDialogType === 'originalCreatives'" label="原始参考素材" name="originalCreatives">
                <div class="refCreative">
                  <a @click="downloadCreative(creativeRequestDetail,'originCreative')" style="margin-left: 20px"><i
                    class="el-icon-download">下载</i></a>
                </div>
                <el-row :gutter="20" class="creative_list" style="margin: 0">
                  <ul class="el-upload-list el-upload-list--picture-card">
                    <li
                      v-for="(creative, i) in creativeRequestDetail.originalCreativeList"
                      :key="i"
                      class="el-upload-list__item is-ready"
                    >
                      <div v-if="creative.creativeUrl === '-1'">上传中</div>
                      <div v-if="creative.creativeUrl === '-2'">上传失败</div>
                      <img
                        v-if="
                          creative.creativeUrl !== '-1' &&
                          creative.creativeUrl !== '-2'
                        "
                        class="el-upload-list__item-thumbnail creative"
                        :src="creative.creativeUrl"
                        alt=""
                        @click="detailCreative(creative,$event)" showdetail="true"
                      />
                    </li>
                  </ul>
                </el-row>
              </div>
            </div>
          </el-form-item>
        </el-row>
        <!-- 成品素材 -->
        <el-row class="product" v-show="creativeRequestDetail.finishedCreativeList != null && creativeRequestDetail.finishedCreativeList.length > 0">
          <div class="product_Search">
            <div style="display: flex">
              <div style="width: 150px;text-align: right;line-height: 28px;margin-right: 17px">设计师:</div>
              <el-select id="id-offer-componets-creativerequest-conmponents-request-check-detail-getCreativeRequestDetailProdList"
                         size="mini" v-model="designers" filterable
                         @click="getCreativeRequestDetailProdList(creativeRequestDetail)"
                         multiple
                         clearable
                         placeholder="请选择">
                <el-option v-for="(item) in allUserList"
                           v-if="creativeRequestDetail.designerIdListWithCreative == null || creativeRequestDetail.designerIdListWithCreative.length == 0 || creativeRequestDetail.designerIdListWithCreative.includes(item.id)"
                           :key="item.id" :value="item.id"
                           :label="item.realName">
                </el-option>
              </el-select>
<!-- <div style="width: 150px;text-align: left;line-height: 28px;margin-left: 17px">共{{creativeRequestDetail.finishedCreativeList.length}}个素材</div> -->

             <div style="width: 150px;text-align: left;line-height: 28px;margin-left: 17px">共{{getCreativeRequestDetailProdListaa(creativeRequestDetail)}}个素材</div>
              <!-- <button @click="count()">11</button> -->
            </div>
          </div>
          <div v-for="(creativeRequestDetailProd,index) in getCreativeRequestDetailProdList(creativeRequestDetail)" :key="index"
               class="product_Body">
            <div class="prod-step">
              <el-steps direction="vertical">
                <el-step v-if="creativeRequestDetailProd.demandIsProd == 1">
                  <div slot="title" class="step-title">
                    <div>成品素材</div>
                    <div>上传时间 {{ creativeRequestDetailProd.date }}</div>
                    <div>设计师 {{getDesignerNameList(creativeRequestDetailProd.designerList)}}</div>
                    <div>制作用时 {{getMakeTimeText(creativeRequestDetailProd.makeTime)}}</div>
                    <div>共{{ creativeRequestDetailProd.creativeList.length }}个素材</div>
                  </div>
                  <div class="product_isUpload_content" slot="description" style="min-height: 240px">
                    <div class="product_isUpload">
                      <div class="product_isUpload_label">成品素材 :</div>
                      <div class="product_isUpload_content">
                        <div>
                          <ul class="el-upload-list el-upload-list--picture-card" style="display: flex;flex-wrap: wrap">
                            <div v-for="(creative, i) in creativeRequestDetailProd.creativeList" :key="i" class="product_border">
                              <li class="el-upload-list__item is-ready">
                                <div v-if="creative.thumbnailUrl === '-1'">上传中</div>
                                <div v-if="creative.thumbnailUrl === '-2'">上传失败</div>
                                <img
                                  v-if="
                          creative.thumbnailUrl !== '-1' &&
                          creative.thumbnailUrl !== '-2'
                        "
                                  class="el-upload-list__item-thumbnail creative"
                                  :src="creative.thumbnailUrl"
                                  alt=""
                                  @click="detailCreative(creative,$event)" showdetail="true"
                                />
                              </li>
                              <div class="productCreativeTest">
                                <el-tooltip class="item" effect="dark" :content="creative.localFilename"
                                            placement="top-start">
                                  <div>
                                    本地名称: {{ creative.localFilename }}
                                  </div>
                                </el-tooltip>
                                <el-tooltip v-if="creative.creator" class="item" effect="dark"
                                            :content="creative.creator"
                                            placement="top-start">
                                  <div>
                                    上传人: {{ creative.creator }}
                                  </div>
                                </el-tooltip>
                                <el-tooltip class="item" effect="dark" :content="creative.shortId" placement="top">
                                  <div v-if="creative.shortId !=null">
                                    短Id: {{ creative.shortId }}
                                  </div>
                                  <div v-if="creative.shortId ===null">
                                    短Id: -
                                  </div>
                                </el-tooltip>
                              </div>
                              <div v-if="getCreativeCheckStatus(creative) == 1">
                                <el-button id="id-offer-componets-creativerequest-conmponents-request-check-detail-finished-product"
                                           type="info" icon="el-icon-video-pause" circle
                                           style="padding: 6px"></el-button>
                                <span class="finished-product">待审</span>
                              </div>
                              <div v-if="getCreativeCheckStatus(creative) == 2">
                                <el-button id="id-offer-componets-creativerequest-conmponents-request-check-detail-getCreativeCheckStatus"
                                           type="success" icon="el-icon-check" circle style="padding: 6px"></el-button>
                                <span class="finished-product">同意</span>
                              </div>
                              <div v-if="getCreativeCheckStatus(creative) == 3">
                                <el-button id="id-offer-componets-creativerequest-conmponents-request-check-detail-getCreativeCheckStatus-two"
                                           type="danger" icon="el-icon-close" circle style="padding: 6px"></el-button>
                                <span class="finished-product">拒绝（优化师）</span>
                              </div>
                              <div v-if="getCreativeCheckStatus(creative) == 4">
                                <el-button id="id-offer-componets-creativerequest-conmponents-request-check-detail-getCreativeCheckStatus-3"
                                           type="danger" icon="el-icon-close" circle style="padding: 6px"></el-button>
                                <span class="finished-product">拒绝（客户）</span>
                              </div>
                              <el-input id="id-offer-componets-creativerequest-conmponents-request-check-detail-finished-product-4"
                                        v-if="getCreativeCheckStatus(creative) == 3" type="textarea" readonly :row="2" v-model="creative.demandAuditComment"></el-input>
                              <el-input id="id-offer-componets-creativerequest-conmponents-request-check-detail-finished-product-5"
                                        v-if="getCreativeCheckStatus(creative) == 4" type="textarea" readonly :row="2" v-model="creative.comments"></el-input>
                            </div>
                          </ul>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-step>
                <el-step v-if="creativeRequestDetailProd.demandIsProd == 0">
                  <div slot="title" class="step-title">
                    <div>制作中素材</div>
                    <div>上传时间 {{ creativeRequestDetailProd.date }}</div>
                    <div>设计师 {{getDesignerNameList(creativeRequestDetailProd.designerList)}}</div>
                    <div>制作用时 {{getMakeTimeText(creativeRequestDetailProd.makeTime)}}</div>
                    <div>共{{ creativeRequestDetailProd.creativeList.length }}个素材</div>
                  </div>
                  <div class="product_isUpload_content" slot="description">
                    <div class="product_isUpload">
                      <div class="product_isUpload_label">制作中素材 :</div>
                      <div class="product_isUpload_content">
                        <div>
                          <ul class="el-upload-list el-upload-list--picture-card" style="display: flex;flex-wrap: wrap">
                            <div v-for="(creative, i) in creativeRequestDetailProd.creativeList" :key="i" class="product_border">
                              <li class="el-upload-list__item is-ready">
                                <div v-if="creative.thumbnailUrl === '-1'">上传中</div>
                                <div v-if="creative.thumbnailUrl === '-2'">上传失败</div>
                                <img
                                  v-if="
                                      creative.thumbnailUrl !== '-1' &&
                                      creative.thumbnailUrl !== '-2'
                                    "
                                  class="el-upload-list__item-thumbnail creative"
                                  :src="creative.thumbnailUrl"
                                  alt=""
                                  @click="detailCreative(creative,$event)" showdetail="true"
                                />
                              </li>
                              <div class="productCreativeTest">
                                <el-tooltip class="item" effect="dark" :content="creative.localFilename"
                                            placement="top-start">
                                  <div>
                                    本地名称: {{ creative.localFilename }}
                                  </div>
                                </el-tooltip>
                                <el-tooltip v-if="creative.creator" class="item" effect="dark"
                                            :content="creative.creator"
                                            placement="top-start">
                                  <div>
                                    上传人: {{ creative.creator }}
                                  </div>
                                </el-tooltip>
                              </div>
                              <el-input type="textarea" readonly :row="2" v-model="creative.content"></el-input>
                            </div>
                          </ul>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-step>
              </el-steps>
            </div>
          </div>
        </el-row>
      </div>
    </el-form>

    <!-- 素材详情-->
    <el-dialog :visible.sync="detailCreativeDialog" append-to-body top="0px;" :modal-append-to-body="false"
               :close-on-click-modal="true"
               :show-close="false" :before-close="closeDetailDialog" width="60%" class="creative-detail-list">
      <div style="text-align: center; width: 100%; height: 100%">
        <div slot="title" style="text-align: right">
          <el-button id="id-offer-componets-creativerequest-conmponents-request-check-detail-closeDetailDialog"
                     class="dialog-close" size="mini" icon="el-icon-close" @click="closeDetailDialog"
                     circle></el-button>
        </div>
        <img :src="detailCreativeUrl" v-show="detailType === 'image'"/>
        <video v-show="detailType === 'video'" ref="video" :src="detailCreativeUrl"
               autoplay="autoplay" controls="controls" class="creative_edit"></video>
      </div>
    </el-dialog>

    <!--需求历史记录-->
    <div v-if="historyDialog">
      <request-history :close-history="closeHistory" :creativeRequestDetail="historyCreativeRequestDetail"
                       :dialogVisible="historyDialog" :userRole="userRole"
      ></request-history>
    </div>
    <div id="downloadContent" style="display: none;"></div>
  </div>
</template>

<script>
import creativeUpload from "/src/components/beetles-upload/creative_upload";
import creativeRequestAppend from "../creativeRequestAppend";
import originCreativeAdd from "../originCreativeAdd";
import {getOfferDesigner} from "@/api/offer/creativerequest";
import requestHistory from "./request-history";
import {getRejectedList, selectAll, selectDetail, selectCreative} from "@/api/offer/creativerequest";
import {findArray, findByProp} from "@/util/util";
import Moment from "moment";
import func from "@/util/func";
import {getAllUser} from "@/api/user";
import JSZip from "jszip";
import FileSaver from "file-saver"

export default {
  name: "request-check-detail",
  components: {
    creativeUpload,
    creativeRequestAppend,
    originCreativeAdd,
    requestHistory,
  },
  props: {
    offerId: String,
    product: Boolean,
    title: String,
    creativeRequestData: Object,
    userRole: Object,
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now() - 24 * 60 * 60 * 1000;
        },
      },
      allUserList: [],
      designers: '',
      form: {
        designers: [],//设计师
        planTime: '',//制作日期
        actualTime: '',//实际完成时间
      },
      historyDialog: false,//需求历史记录弹窗
      historyCreativeRequestDetail: null,
      productIndex: '',
      creativeRequestId: "",
      existedCreativeIds: "",
      designerList: [],//设计师列表
      index: "", //参考素材的下标
      detailCreativeDialog: false, //素材详情
      detailType: {}, //素材详情弹窗-素材类型
      detailCreativeUrl: "", //素材详情弹窗-素材URL
      eventSeq : 1,
    };
  },
  created() {
    console.log(this.creativeRequestData)
    getAllUser({statusList: '0,1,2', isAll: true}).then(res => {
      this.allUserList = res.data.data
    });
    this.form.designers = func.toList(this.creativeRequestData.creativeRequest.designers);
    this.form.planTime = this.creativeRequestData.creativeRequest.planTime
    this.form.actualTime = this.creativeRequestData.creativeRequest.actualTime

    this.creativeRequestData.creativeRequestDetailList.forEach((creativeRequestDetail) => {
      if (!creativeRequestDetail.appendFileList) {
        creativeRequestDetail.appendFileList = [];
        if (creativeRequestDetail.appendFiles != null && creativeRequestDetail.appendFiles.startsWith('[')) {
          creativeRequestDetail.appendFileList = JSON.parse(creativeRequestDetail.appendFiles);
        }
      }
      this.creativeTypeClick(creativeRequestDetail,'creatives');
      this.buildDesignerListWithCreative(creativeRequestDetail);
    });
    getOfferDesigner(this.offerId).then((res) => {
      this.designerList = res.data.data;
    });
  },
  methods: {
    buildDesignerListWithCreative(creativeRequestDetail) {
      let designerIdList = [];
      creativeRequestDetail.finishedCreativeList.forEach((creative) => {
        let idList = (creative.designer || '').split(',');
        idList.forEach(id=>{
          if(!designerIdList.includes(id)) {
            designerIdList.push(id);
          }
        })
      });
      creativeRequestDetail.designerIdListWithCreative = designerIdList;
    },
    /**
     * 设置参考素材title
     */
    creativeTypeClick(creativeRequestDetail,tab) {
      creativeRequestDetail.creativeDialogType = tab;
      this.eventSeq ++;
    },

    //素材详情
    /*
      查看素材
     */
    detailCreative(row, event) {
      if (event == null || event.target.getAttribute('showdetail') != 'true') {
        return;
      }
      let creativeDetailInfo = this.getCreativeDetailInfo(row);
      if (!creativeDetailInfo) {
        return;
      }
      this.detailCreativeDialog = true;
      this.detailType = creativeDetailInfo.detailType;
      this.detailCreativeUrl = creativeDetailInfo.detailCreativeUrl;
    },
    /**
     * 判断素材类型
     */
    getCreativeDetailInfo(row) {
      let url = row.creativeUrl;
      if (!url) {
        url = row.link;
      }
      if (!url) {
        return null;
      }
      let div = url.indexOf('?');
      if (div != -1) {
        url = url.substring(0, div);
      }
      let type;
      let urlType = url.split(".")[url.split(".").length - 1];
      let imgList = ["jpg", "jpeg", "png", "gif", "bmp"];
      let videoList = ["mp4", "mov", "avi", "mp3", "ogg", "rmvb", "mkv"];
      if (imgList.includes(urlType)) {
        type = "image";
      } else if (videoList.includes(urlType)) {
        type = "video";
      }
      return {detailType: type, detailCreativeUrl: url};
    },
    /**
     * 素材详情 关闭
     */
    closeDetailDialog() {
      this.detailCreativeDialog = false;
      this.$refs.video.pause();
    },
    /**
     * 表单验证
     */
    validateForm() {
      let flag = false;
      this.$refs.form.validate((valid) => {
        if (valid) {
          flag = true;
        } else {
          flag = false;
        }
      });
      return flag;
    },
    getFileList(creativeRequestDetail) {
      let fileList = [];
      if (creativeRequestDetail.appendFiles != null && creativeRequestDetail.appendFiles.startsWith('[')) {
        let appendFileList = JSON.parse(creativeRequestDetail.appendFiles);
        appendFileList.forEach((appendFile) => {
          fileList.push({
            name: appendFile.filename,
            url: appendFile.fileUrl,
          })
        });
      }
      return fileList;
    },
    /**
     * 查看需求沟通历史记录
     */
    creativeRequestHistory(index, item) {
      this.historyCreativeRequestDetail = item;
      this.historyDialog = true
    },
    /**
     * 关闭需求沟通历史记录
     */
    closeHistory() {
      this.historyDialog = false
    },
    getFirstPlatform(val) {
      if (val == null || val.length == 0) {
        return '';
      } else if (typeof val == 'string') {
        return val.split(',')[0];
      } else {
        return val[0];
      }
    },

    getCreativeRequestDetailProdList(creativeRequestDetail) {
      // ############################
      // 同编辑页的creativeRequestDetailProdList，但同批次内按照(1、优先展示被拒素材>通过素材>待审素材2、被拒素材显示由客户拒绝还是由优化师拒绝)排序
      // ############################

      //显示层级：批次时间（但显示日期）=>状态
      let prodList = [];//日期=>成品
      let mapProdList = {};
      let timeMap = {};

      let selectedDesignerList = [];
      if (this.designers != null && this.designers.length > 0) {
        selectedDesignerList = this.designers;
      }

      if (creativeRequestDetail.finishedCreativeList != null) {
        creativeRequestDetail.finishedCreativeList.forEach((creative) => {
          if(selectedDesignerList.length > 0) {
            let selectedDesigner = false;
            if(creative.designer != null && creative.designer != '') {
              let creativeDesignerList = creative.designer.split(',');
              for(let d=0;d<creativeDesignerList.length;d++) {
                if(selectedDesignerList.includes(creativeDesignerList[d])) {
                  selectedDesigner = true;
                  break;
                }
              }
            }
            if(!selectedDesigner) {
              return;
            }
          }
          //前后10秒为一组，避免同一次提交时间延迟偏差
          let time = Moment(new Date(creative.createTime)).format('YYYY-MM-DD HH:mm:ss');
          for(let t=0;t<20;t++) {
            let checkTime = timeMap[Moment(new Date(creative.createTime)).subtract(10 - t,'seconds').format('YYYY-MM-DD HH:mm:ss')];
            if(checkTime) {
              time = checkTime;
              break;
            }
          }
          timeMap[time] = time;
          let bundleId = (creative.bundleId != null && creative.bundleId != -1)?creative.bundleId:'';
          let key = (bundleId == '')?(time + '|' + creative.demandIsProd):(bundleId + '|' + creative.demandIsProd);
          let theProd = mapProdList[key];
          if (!theProd) {
            theProd = {
              date: Moment(new Date(creative.createTime)).format('YYYY-MM-DD'),//仅用于显示
              bundleId: bundleId,
              bundleCreateTime: creative.createTime,
              makeTime: creative.makeTime,
              demandIsProd: creative.demandIsProd,//没有要求按这个排序，但总觉得不排序不可靠
              designerList: [],
              creativeList: [],
            };
            mapProdList[key] = theProd;
            prodList.push(theProd);
          }
          theProd.creativeList.push(creative);
          let designerList = (creative.designer || '').split(',');
          designerList.forEach((one)=>{
            if(!theProd.designerList.includes(one)) {
              theProd.designerList.push(one);
            }
          })
        });
      }
      prodList.sort((a, b) => {
        if(a.bundleCreateTime > b.bundleCreateTime) {
          return -1;
        }
        if(a.bundleCreateTime < b.bundleCreateTime) {
          return 1;
        }
        if(a.demandIsProd != b.demandIsProd) {
          if(a.demandIsProd == 1) {
            return -1;
          } else {
            return 1;
          }
        }
        return 0;
      });
      prodList.forEach(item=>{
        item.creativeList.sort((a,b)=>{
          let a_status = a.demandStatus;
          if(a.status == 3) {
            a_status = a.status;
          }
          let b_status = b.demandStatus;
          if(b.status == 3) {
            b_status = a.status;
          }

          if(a_status != b_status) {
            if(a_status == 3) {
              return -1;
            }
            if(b_status == 3) {
              return 1;
            }
            if(a_status == 2) {
              return -1;
            }
            if(b_status == 2) {
              return 1;
            }
          }
          return 0;
        })
      });
      return prodList;

    },
      getCreativeRequestDetailProdListaa(creativeRequestDetail) {
      // ############################
      // 同编辑页的creativeRequestDetailProdList，但同批次内按照(1、优先展示被拒素材>通过素材>待审素材2、被拒素材显示由客户拒绝还是由优化师拒绝)排序
      // ############################

      //显示层级：批次时间（但显示日期）=>状态
      let prodList = [];//日期=>成品
      let mapProdList = {};
      let timeMap = {};

      let selectedDesignerList = [];
      if (this.designers != null && this.designers.length > 0) {
        selectedDesignerList = this.designers;
      }

      if (creativeRequestDetail.finishedCreativeList != null) {
        creativeRequestDetail.finishedCreativeList.forEach((creative) => {
          if(selectedDesignerList.length > 0) {
            let selectedDesigner = false;
            if(creative.designer != null && creative.designer != '') {
              let creativeDesignerList = creative.designer.split(',');
              for(let d=0;d<creativeDesignerList.length;d++) {
                if(selectedDesignerList.includes(creativeDesignerList[d])) {
                  selectedDesigner = true;
                  break;
                }
              }
            }
            if(!selectedDesigner) {
              return;
            }
          }
          //前后10秒为一组，避免同一次提交时间延迟偏差
          let time = Moment(new Date(creative.createTime)).format('YYYY-MM-DD HH:mm:ss');
          for(let t=0;t<20;t++) {
            let checkTime = timeMap[Moment(new Date(creative.createTime)).subtract(10 - t,'seconds').format('YYYY-MM-DD HH:mm:ss')];
            if(checkTime) {
              time = checkTime;
              break;
            }
          }
          timeMap[time] = time;
          let bundleId = (creative.bundleId != null && creative.bundleId != -1)?creative.bundleId:'';
          let key = (bundleId == '')?(time + '|' + creative.demandIsProd):(bundleId + '|' + creative.demandIsProd);
          let theProd = mapProdList[key];
          if (!theProd) {
            theProd = {
              date: Moment(new Date(creative.createTime)).format('YYYY-MM-DD'),//仅用于显示
              bundleId: bundleId,
              bundleCreateTime: creative.createTime,
              makeTime: creative.makeTime,
              demandIsProd: creative.demandIsProd,//没有要求按这个排序，但总觉得不排序不可靠
              designerList: [],
              creativeList: [],
            };
            mapProdList[key] = theProd;
            prodList.push(theProd);
          }
          theProd.creativeList.push(creative);
          let designerList = (creative.designer || '').split(',');
          designerList.forEach((one)=>{
            if(!theProd.designerList.includes(one)) {
              theProd.designerList.push(one);
            }
          })
        });
      }
      prodList.sort((a, b) => {
        if(a.bundleCreateTime > b.bundleCreateTime) {
          return -1;
        }
        if(a.bundleCreateTime < b.bundleCreateTime) {
          return 1;
        }
        if(a.demandIsProd != b.demandIsProd) {
          if(a.demandIsProd == 1) {
            return -1;
          } else {
            return 1;
          }
        }
        return 0;
      });
      prodList.forEach(item=>{
        item.creativeList.sort((a,b)=>{
          let a_status = a.demandStatus;
          if(a.status == 3) {
            a_status = a.status;
          }
          let b_status = b.demandStatus;
          if(b.status == 3) {
            b_status = a.status;
          }

          if(a_status != b_status) {
            if(a_status == 3) {
              return -1;
            }
            if(b_status == 3) {
              return 1;
            }
            if(a_status == 2) {
              return -1;
            }
            if(b_status == 2) {
              return 1;
            }
          }
          return 0;
        })
      });
      let i=prodList.length;
      // let arr=prodList;
      let sum=0;
      for(let j=0;j<i;j++){

        sum=sum+prodList[j].creativeList.length

      }
      console.log('arr',sum)
      return sum;

    },
    getDesignerNameList(designers) {
      if (designers == null || designers.length == 0) {
        return '';
      }
      let list = null;
      if (typeof (designers) == 'string') {
        list = func.toList(designers);
      } else {
        list = designers;
      }
      let nameList = [];
      list.forEach(id => {
        let name = findByProp(this.allUserList, id, 'id', 'realName');
        nameList.push(name);
      })
      return nameList.join(',');
    },
    getMakeTimeText(makeTime) {
      if(makeTime != null && makeTime > 0) {
        let hour = Math.floor(makeTime / 3600);
        let minute = Math.floor(makeTime / 60) % 60;

        if(hour > 0 || minute > 0) {
          return ((hour > 0)?(hour + '小时'):'') + ((minute > 0)?(minute + '分钟'):'');
        }
      }
      return '0分钟';
    },
    getCreativeCheckStatus(creative) {
      if(creative.demandStatus == 3) {
        return 3;//优化师拒绝
      }
      if(creative.demandStatus == 2) {
        if(creative.status == 3) {
          return 4;//客户拒绝
        }
        return 2;//通过
      }
      return 1;//待审核
    },
    downloadCreative(creativeRequestDetail,type) {
      let downloadIds = []
      if (type == 'creative') {
        // creativeRequestDetail.creativeList.map(item => {
        //   downloadIds.push(item.id)
        // })
        if(creativeRequestDetail.creativeList.length === 1) {
          this.downVideo(creativeRequestDetail.creativeList[0].creativeUrl)
        } else if (creativeRequestDetail.creativeList.length > 1) {
          let _this = this;
          let zip = new JSZip();
          let promises = [];
          //压缩包下载
          let loading = this.$loading({
            lock: true,
            text: '下载中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          creativeRequestDetail.creativeList.map((item, index) => {
            const promise = _this.downloadUrlQiniu(item.creativeUrl).then(res => {
              console.log('res',res)
              zip.file(item.creativeUrl.substr(item.creativeUrl.lastIndexOf('/')),
                res, {binary: true}); //
            })
            promises.push(promise);
          })
          Promise.all(promises).then(() => {
            zip.generateAsync({type: "blob"}).then(res => {
              // 生成二进制流
              console.log(res)
              FileSaver.saveAs(res, 'download' + Moment(new Date()).format('YYYYMMDDhhmmss')); // 利用file-saver保存文件,可以改成自己想要的压缩包名称
              loading.close();
            });
          }).catch((e) => {
            loading.close();
            _this.$message.error('素材下载失败，请重试！');
            console.error(e);
          });
        }
        return;
      } else if (type == 'originCreative') {
        // creativeRequestDetail.originalCreativeList.map(item => {
        //   downloadIds.push(item.id)
        // })
        if(creativeRequestDetail.originalCreativeList.length === 1) {
          this.downVideo(creativeRequestDetail.originalCreativeList[0].creativeUrl)
        } else if (creativeRequestDetail.originalCreativeList.length > 1) {
          let _this = this;
          let zip = new JSZip();
          let promises = [];
          //压缩包下载
          let loading = this.$loading({
            lock: true,
            text: '下载中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          creativeRequestDetail.originalCreativeList.map((item, index) => {
            const promise = _this.downloadUrlQiniu(item.creativeUrl).then(res => {
              console.log('res',res)
              zip.file(item.creativeUrl.substr(item.creativeUrl.lastIndexOf('/')),
                res, {binary: true}); //
            })
            promises.push(promise);
          })
          Promise.all(promises).then(() => {
            zip.generateAsync({type: "blob"}).then(res => {
              // 生成二进制流
              console.log(res)
              FileSaver.saveAs(res, 'download' + Moment(new Date()).format('YYYYMMDDhhmmss')); // 利用file-saver保存文件,可以改成自己想要的压缩包名称
              loading.close();
            });
          }).catch((e) => {
            loading.close();
            _this.$message.error('素材下载失败，请重试！');
            console.error(e);
          });
        }
        return;
      } else if (type == 'rejectedCreative') {
        // this.creativeRequestDetail.rejectedCreativeList.map(item => {
        //   downloadIds.push(item.id)
        // })
        if(creativeRequestDetail.rejectedCreativeList.length === 1) {
          this.downVideo(creativeRequestDetail.rejectedCreativeList[0].creativeUrl)
        } else if (creativeRequestDetail.rejectedCreativeList.length > 1) {
          let _this = this;
          let zip = new JSZip();
          let promises = [];
          //压缩包下载
          let loading = this.$loading({
            lock: true,
            text: '下载中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          creativeRequestDetail.rejectedCreativeList.map((item, index) => {
            const promise = _this.downloadUrlQiniu(item.creativeUrl).then(res => {
              console.log('res',res)
              zip.file(item.creativeUrl.substr(item.creativeUrl.lastIndexOf('/')),
                res, {binary: true}); //
            })
            promises.push(promise);
          })
          Promise.all(promises).then(() => {
            zip.generateAsync({type: "blob"}).then(res => {
              // 生成二进制流
              console.log(res)
              FileSaver.saveAs(res, 'download' + Moment(new Date()).format('YYYYMMDDhhmmss')); // 利用file-saver保存文件,可以改成自己想要的压缩包名称
              loading.close();
            });
          }).catch((e) => {
            loading.close();
            _this.$message.error('素材下载失败，请重试！');
            console.error(e);
          });
        }
        return;
      } else if (downloadIds.length === 0) {
        this.$message({
          type: 'warning',
          message: '没有可下载的素材!'
        })

        return
      }
      // console.log('下载',creativeRequestDetail)
      // const creatives = downloadIds.join(",");
      // // const type = this.form.type;
      // let content = document.getElementById("downloadContent");
      // var aLink = document.createElement("a");
      // content.appendChild(aLink);
      // aLink.href = "/api/beetles-offer/creativerequest/download-creatives?creativeIds=" + creatives;
      // aLink.id = "downloadVideo";
      // let linkEle = document.getElementById(aLink.id);
      // linkEle.click();
      // linkEle.remove();
    },
    downVideo (url){
      var xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'arraybuffer';    // 返回类型blob
      xhr.onload = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          let blob = this.response;
          // 转换一个blob链接
          let u = window.URL.createObjectURL(new Blob([blob]))
          let a = document.createElement('a');
          a.download = url.substr(url.lastIndexOf('/'));
          a.href = u;
          a.style.display = 'none'
          document.body.appendChild(a)
          a.click();
          a.remove();
        }
      };
      xhr.send()
    },
    downloadUrlQiniu(url) {
      return new Promise((resolve, reject) => {
        if (!url.startsWith('http')) {
          return;
        }
        if (!url.startsWith('https')) {
          let urlArr = url.split("://")
          if (urlArr.length < 2) {
            return;
          }
          url = "https://" + urlArr[1]
        }
        fetch(url, {
          method: 'GET',
          headers: {
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
          }
        }).then(res => {
          resolve(res.blob())
        }).catch(err => {
          reject(err)
        })
      })
    },
  },
};
</script>

<style scoped lang="scss">
.creative_request_upload-body {
  width: 100%;
  background-color: whitesmoke;
  border: 1px solid #e8e8e8;
  border-radius: 10px;
  padding-top: 1em;
  margin-top: 3em;
}

.creative_request_upload-body-edit {
  width: 100%;
  margin: 10px auto;
  -webkit-box-shadow: 2px 2px 19px 2px rgba(0, 0, 0, 0.18);
  box-shadow: 2px 2px 19px 2px rgba(0, 0, 0, 0.18);
  border-radius: 20px;
  padding: 15px;
}

.refCreative {
  a {
    cursor: pointer;
  }
}

.request_creativeNum {
  /deep/ .el-input.is-disabled .el-input__inner {
    color: black;
  }
}

.creative_list {
  /deep/ .el-upload-list__item {
    text-align: center;
    vertical-align: middle;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  /deep/ .el-upload-list--picture-card {
    display: flex;
    flex-wrap: wrap;
  }

  .creative {
    max-height: 100%;
    max-width: 100%;
    height: auto;
    width: auto;
    vertical-align: middle;
  }
}

.creative-detail-list {
  .dialog-close {
    margin-bottom: 20px;
    background-color: rgba(255, 255, 255, 0);
    color: white;
  }

  /deep/ .el-dialog {
    background: rgba(255, 255, 255, 0);
    -webkit-box-shadow: none;
    box-shadow: none;
  }

  /deep/ .el-dialog__header {
    padding: 0;
  }

  img {
    width: auto;
    height: auto;
    max-width: 80%;
    max-height: 80vh;
  }

  /deep/ video {
    width: auto;
    height: auto;
    max-width: 80%;
    max-height: 80vh;
  }
}

.product_Search {
  display: flex;
  flex-direction: row;
}

.product_Body {
  width: 90%;
  margin: 1em auto auto auto;

  .product_UploadDate {
    color: #00a2ff;
    font-weight: 600;
    border-bottom: solid 2px #BDC3C7;
    padding-bottom: 3px;
    padding-left: 3em;
  }

  .product_isUpload {
    margin-top: 10px;
    display: flex;

    .product_isUpload_label {
      width: 100px;
    }

    .product_isUpload_content {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
    }

    /deep/ .el-upload-list--picture-card .el-upload-list__item {
      overflow: inherit;
    }

    .product_border {
      width: 150px;
      height: 330px;
      margin-right: 10px;
      box-sizing: border-box;

      .productCreativeTest {
        font-size: 14px;
        margin: 5px;

        div {
          width: 100%;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
          line-height: 2em;
        }
      }
    }
  }
}

.checkRequestHistory {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-end;
  line-height: 28px;
  padding-right: 3em;

  a {
    padding-right: 2em;
    cursor: pointer;
  }
}

.finished-product {
  margin-left: 12px;
  font-size: 15px;
}

.tabs_creative {
  display: flex;
  border: 1px solid rgba(22, 132, 252, 100);
  border-radius: 10px;
  text-align: center;
  width: 320px;
}

.tags_true {
  color: white;
  background: #1684FC 10000%;
}

.tags_false {
  color: #1684FD;
  background: white;
}

.product {
  width: 98%;
  border-radius: 10px;
  color: #101010;
  font-size: 14px;
  text-align: center;
  padding-top: 2em;
  font-family: Roboto;
  margin: auto auto 2em auto;
  border: 1px solid #e8e8e8;
  background: white;
  padding-bottom: 1em;
}

.prod-step {
  width: 94%;
  margin: 0 auto;

  .step-title {
    display: flex;
    color: black;
    font-size: 14px;

    div {
      margin-right: 2em;
      color: #333;
    }
  }

  /deep/ .el-step__icon-inner {
    display: none;
  }

  /deep/ .el-step.is-vertical .el-step__line {
    top: 20px;
  }

  /deep/ .el-step__icon {
    width: 10px;
    height: 10px;
  }

  .prod_index {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    line-height: 24px;
    background-color: rgba(22, 132, 253, 100);
    color: rgba(255, 255, 255, 100);
    font-size: 14px;
    text-align: center;
    font-family: Roboto;
  }

}
</style>
